//index.js
//获取应用实例
var app = getApp();
var util = require('../../../utils/util.js');
Page({
  data: {
    cardInfo: {},
    tableNumber: 0,
    cartResult: [],
    proSumMoney: 0,
    payMoney: 0,
    remark: '',
    selList: '',
    payType: 0,
    discount: '',//管理员打的折扣
    vall: '',
    cutmoney: 0
  },
  addFood: function () {
    wx.reLaunch({
      url: '/pages/classes-new/index',
    })
  },

  bindDiscount: function (e) {
    this.setData({
      discount: e.detail.value
    })
  },

  //获取餐桌设置
  getDiningTable: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + "/api/Restaurant/GetDiningTable?id=" + app.globalData.diningSid,
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            tableNumber: res.data.Data.TableNumber,
            tableName: res.data.Data.Name
          })
        }
      },
    })
  },

  getInfo: function () {
    let that = this;
    let cardid = wx.getStorageSync("cardId");
    wx.request({
      url: app.globalData.host + '/api/Staff/GetInfo?id=' + cardid,
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            cardInfo: res.data.Data
          })
        }
      }
    })
  },

  confirmOrder: function (type = 0) {
    var that = this;
    wx.showLoading();
    var said = 0;
    var postData = {
      Uid: app.globalData.userInfo.Uid,
      SaId: said,
      Sid: app.globalData.diningSid
    }
    let url = app.globalData.host + '/api/order/SessionConfirmOrder';
    if (type == 2) {//确认订单
      url = app.globalData.host + '/api/order/SubmitSessionPreOrder';
      postData = {
        Sid: app.globalData.diningSid,
        SaId: said,
        Uid: app.globalData.userInfo.Uid,
        BuyerRemark: that.data.remark,
        SelList: that.data.selList
      }
    }
    //初始化订单
    wx.request({
      url: url,
      method: 'POST',
      data: postData, // 设置请求的 参数
      success: (res) => {
        wx.hideLoading();
        wx.setNavigationBarTitle({
          title: '待付款订单',
        })
        if (res.data.Code == 0) {
          var confirm = [];
          let cartResult = [];
          //订单确认成功
          if (res.data.Data){
            confirm = res.data.Data;
            cartResult = confirm.StoreOrderList[0].StoreCartInfo.CartProductList;
            for (let i = 0; i < cartResult.length; i++) {
              if (cartResult[i].OrderProductInfo.ShowImg.indexOf('ps') != -1) {
                cartResult[i].OrderProductInfo.ShowImg = util.formatAvaterByProHead(cartResult[i].OrderProductInfo.ShowImg);
              } else {
                cartResult[i].OrderProductInfo.ShowImg = util.formatAvater(cartResult[i].OrderProductInfo.ShowImg, 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/product/editor/');
              }
              cartResult[i].OrderProductInfo.OptionName = '';
              if (cartResult[i].OrderProductInfo.OptionIds) {
                that.getProductOptionList(cartResult[i].OrderProductInfo.OptionIds, function (name) {
                  cartResult[i].OrderProductInfo.OptionName = name;
                });
              }
            }
            setTimeout(function(){
              that.setData({
                cartResult: cartResult,
                proSumMoney: res.data.Data.AllProductAmount,
                payMoney: res.data.Data.AllOrderAmount,
                remark: res.data.Data.BuyerRemark,
                cutmoney: res.data.Data.Discount.toFixed(2),
                vall: ''
              });
            },500)
            
          }else{
            if(that.data.payType == 2 && type == 2){//先用餐：确认订单后再初始化订单
              that.confirmOrder();
            }
          }
        }
      }
    })
  },
  chooseGoods: function(e){
    let that = this;
    let pid = e.currentTarget.dataset.pid;
    let cartResult = that.data.cartResult;
    for(let i = 0; i < cartResult.length; i++){
      if(cartResult[i].OrderProductInfo.Pid == pid){
        cartResult[i].IsSelected = !cartResult[i].IsSelected;
      }
    }
    that.setData({
      cartResult: cartResult
    })
    that.inDiscount()
  },
  // 产品规格
  getProductOptionList: function (optionids, callback) {
    wx.request({
      url: app.globalData.host + '/api/product/GetProductOptionList?optionIds=' + optionids,
      success: function (res) {
        if (res.data.Code == 0) {
          let name = '';
          let list = res.data.Data;
          for (let i = 0; i < list.length; i++) {
            name += list[i].OptionList[0].Name + '/';
          }
          callback(name.substr(0, name.length - 1));
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  //显示折扣inDiscount
  inDiscount: function (e) {
    var val = this.data.discount;
    let payMoney = this.data.payMoney;
    if (e) {
      var val = e.detail.value
      if (val == "" || val > 100) {
        var val = 100
      }
      this.setData({
        discount: val
      })
    }
    let proSumMoney = this.data.proSumMoney;
    let cutmoney = this.data.cutmoney;
    let cartResult = this.data.cartResult;
    if (val) {
      let canCutmoneyGoods = 0;
      for(let i = 0; i < cartResult.length; i++){
        if(cartResult[i].IsSelected){
          canCutmoneyGoods += cartResult[i].OrderProductInfo.ShopPrice * cartResult[i].OrderProductInfo.BuyCount
        }
      }
      // payMoney = parseFloat(proSumMoney * (val / 100)).toFixed(2);
      cutmoney = parseFloat(canCutmoneyGoods * (1 - val / 100)).toFixed(2);
      payMoney = parseFloat(proSumMoney-cutmoney).toFixed(2);
    }

    this.setData({
      payMoney: payMoney,
      cutmoney: cutmoney
    })
  },

  onShow: function () {
    var that = this;
    if (app.globalData.userInfo) {
      that.confirmOrder();
    } else {
      setTimeout(function () {
        this.onShow();
      }.bind(that), 1000)
    }
  },

  onLoad: function (e) {
    this.getDiningTable();
    let paytype = wx.getStorageSync('paytype');
    this.getInfo();
    this.setData({
      payType: paytype
    })
  },

  //确认结算订单
  createOrder: function (e) {
    var that = this;
    wx.showLoading({
      title: '提交中',
    })
    wx.request({
      url: app.globalData.host + '/api/Cart/SetSessionDiscount?storeId=' + app.globalData.storeId + '&sid=' + app.globalData.diningSid + '&discount=' + that.data.cutmoney + '&BuyerRemark=' + that.data.remark,
      success: (res) => {
        wx.hideLoading();
        if (res.data.Code != 0) {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
          return;
        } else {
          wx.showToast({
            title: '订单确认成功！',
          })
        }
      }
    })
  },
  // 减数量
  jianShopCar: function (e) {
    let that = this;
    var pid = e.currentTarget.dataset.pid;
    let count = e.currentTarget.dataset.count;
    let recordId = e.currentTarget.dataset.recordid;
    if (count < 2) {
      wx.showModal({
        title: '提示',
        content: '是否删除?',
        success: function (res) {
          if (res.confirm) {
            that.jianShopCarConfirm(pid, count, recordId);
          }
        }
      })
    } else {
      that.jianShopCarConfirm(pid, count, recordId);
    }
  },
  jianShopCarConfirm: function (pid, count, recordId) {
    var that = this;
    let cartResult = that.data.cartResult;
    let sellist = '';
    for (let i = 0; i < cartResult.length; i++) {
      if (cartResult[i].OrderProductInfo.Pid == pid) {
        sellist = '0_' + pid;
        break;
      }
    }
    wx.request({
      url: app.globalData.host + '/api/cart/ChangeSessionProductCount',
      data: {
        pid: pid,
        buyCount: count - 1,
        sid: app.globalData.diningSid,
        selList: sellist,
        recordId: recordId,
        isManage: 1
      },
      success: function (res) {
        if (res.data.Code == 0) {
          that.confirmOrder();
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  addShopCar: function (e) {
    var that = this;
    var pid = e.currentTarget.dataset.pid;
    let buynum = e.currentTarget.dataset.buynum;
    let recordid = e.currentTarget.dataset.recordid;
    let selList = '0_' + pid;
    that.data.selList = selList;
    wx.request({
      url: app.globalData.host + '/api/Store/Product?pid=' + pid,
      success: function (res) {
        if (res.data.Code == 0) {
          var p = res.data.Data;
          if (p.ProductInfo.State == 1) {
            wx.showModal({
              title: '提示',
              content: '商品已下架',
              showCancel: false
            })
            return;
          }
          if (p.StockNumber <= buynum) {
            wx.showModal({
              title: '提示',
              content: '商品库存不足',
              showCancel: false
            })
            return;
          }
          if (p.SinglePromotionInfo) {
            if (p.SinglePromotionInfo.DayBuyCount > 0) {//每天限购一份
              wx.showToast({
                title: '每天限购一份',
                duration: 1000
              })
              return;
            } else {
              wx.showToast({
                title: '限购一份',
                duration: 1000
              })
              return;
            }
          }
          wx.request({
            url: app.globalData.host + '/api/cart/ChangeSessionProductCount',
            data: {
              pid: pid,
              buyCount: buynum + 1,
              sid: app.globalData.diningSid,
              selList: selList,
              recordId: recordid,
              isManage: 1
            },
            success: function (res) {
              if (res.data.Code == 0) {
                that.confirmOrder();
              } else {
                wx.showModal({
                  title: '提示',
                  content: res.data.Message,
                  showCancel: false
                })
              }
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      },
    })
  },
  


  //手输金额
  getDiscountVule: function (e) {
    var zongjia = this.data.proSumMoney;
    var vall = e.detail.value;
    if (vall > zongjia) {
      wx.showModal({
        title: '提示',
        content: '最终折扣金额大于原订单金额',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      vall = zongjia;
    }
    if (vall == '') {
      vall = zongjia;
    }
    var cutmoney = (zongjia - vall).toFixed(2)
    if (cutmoney < 0) {
      cutmoney = 0
    }
    let payMoney = vall;
    this.setData({
      cutmoney: cutmoney,
      vall: vall,
      payMoney: payMoney
    })
  },

  //当输入金额大于总金额返回最大金额
  bindReplaceInput: function (e) {
    this.setData({
      vall: e.detail.value
    })
  }
})
